<template>
  <div v-loading.fullscreen.lock="loading" element-loading-text="加载中..." :class="['aui-wrapper', { 'aui-sidebar--fold': sidebarFold }]">
    <template v-if="!loading">
      <main-navbar />
      <main-sidebar />
      <div class="aui-content__wrapper">
        <main-content v-if="!contentIsNeedRefresh" />
      </div>
    </template>
  </div>
</template>

<script setup>
import MainNavbar from './main-navbar.vue'
import MainSidebar from './main-sidebar.vue'
import MainContent from './main-content.vue'
import debounce from 'lodash/debounce'
import {computed, ref, watch} from "vue";
import {useRoute} from "vue-router";
import http from "../utils/request.js";
import {useStore} from "vuex";
import {message} from "../utils/commonScript.js";

const route = useRoute()
const store = useStore()
const loading = ref(true)

const contentIsNeedRefresh = computed(() => {
  return store.state.contentIsNeedRefresh
})
const sidebarFold = computed(() => {
  return store.state.sidebarFold
})
// 窗口改变大小
const windowResizeHandle = () => {
  store.commit('setSidebarFold',document.documentElement['clientWidth'] <= 992 || false)
  window.addEventListener('resize', debounce(() => {
    store.commit('setSidebarFold',document.documentElement['clientWidth'] <= 992 || false)
  }, 150))
}
// 路由, 监听
const routeHandle = (route) => {
  if (!route.meta.isTab) {
    return false
  }
  let tab = store.state.contentTabs.filter(item => item.name === route.name)[0];
  if (!tab) {
    tab = {
      ...window.SITE_CONFIG['contentTabDefault'],
      ...route.meta,
      'name': route.name,
      'params': { ...route.params },
      'query': { ...route.query }
    }
   store.state.contentTabs = store.state.contentTabs.concat(tab)
  }
  store.state.sidebarMenuActiveName = tab.menuId
  store.state.contentTabsActiveName = tab.name
}

// 获取当前管理员信息
const getUserInfo = () => {
  return http.get('/sys/user/info').then(({ data: res }) => {
    if (res.code !== 0) {
      return message.error(res.msg)
    }
    store.state.user.id = res.data.id
    store.state.user.name = res.data.username
    store.state.user.superAdmin = res.data.superAdmin
  }).catch(() => {})
}

// 获取权限
const getPermissions = () => {
  return http.get('/sys/menu/permissions').then(({ data: res }) => {
    if (res.code !== 0) {
      return message.error(res.msg)
    }
    window.SITE_CONFIG['permissions'] = res.data
  }).catch(() => {})
}
const init = () => {
  Promise.all([
    getUserInfo(),
    getPermissions()
  ]).then(() => {
    loading.value = false
  })
}

watch(()=> route, routeHandle,{
  deep: true
})

windowResizeHandle()
routeHandle(route)
init()

</script>
